package com.qian.ddj.pay.util.shyqUtil;


import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.TreeMap;

public class PayUtils {

        private static LocalHostNameVerify localHostNameVerify = new LocalHostNameVerify();
        private static LocalTrustManager trustManager = new LocalTrustManager();




   private static class LocalHostNameVerify implements HostnameVerifier{

         @Override
         public boolean verify(String s, SSLSession sslSession) {
             return false;
         }
     }
   private static class LocalTrustManager  implements X509TrustManager{

        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }


    private static HttpURLConnection getConnection(String requestUrl) throws IOException, NoSuchAlgorithmException, KeyManagementException {
            URL url = new URL(requestUrl);
            HttpURLConnection urlConnection;

            if (url.getProtocol().equals("https")){
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
                httpsURLConnection.setHostnameVerifier(localHostNameVerify);
                SSLContext tls = SSLContext.getInstance("TLS");
                tls.init(null, new TrustManager[]{trustManager}, null);
                httpsURLConnection.setSSLSocketFactory(tls.getSocketFactory());
                urlConnection = httpsURLConnection;
            }else {
                urlConnection =(HttpURLConnection) url.openConnection();
            }
            urlConnection.setReadTimeout(10000);
            urlConnection.setConnectTimeout(10000);
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            return urlConnection;

    }


    private static String buildQueryParmas(Map<String, String> params) throws UnsupportedEncodingException {
        StringBuffer buffer = new StringBuffer();
        for (Map.Entry<String, String> entry:params.entrySet()){
            String content = "";
            if (entry.getValue()==null || entry.getValue().trim().equals("")){
                content = "";
            }else{
                content = URLEncoder.encode(entry.getValue(), "UTF-8");
            }

            buffer.append(entry.getKey()).append("=").append(content).append("&");
        }
        return buffer.substring(0, buffer.length()-1);
    }



    public static String makeRequest(Map<String, String> params, String requestUrl){
        try {
            HttpURLConnection connection = getConnection(requestUrl);
            String queryParmas = buildQueryParmas(params);
            System.out.println(queryParmas);
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(queryParmas.getBytes());
            InputStream inputStream = connection.getInputStream();
            BufferedReader reader =new BufferedReader(new InputStreamReader(new BufferedInputStream(inputStream)));
            StringBuffer buffer = new StringBuffer();
            String line = null;
            while ((line= reader.readLine())!= null){
                    buffer.append(line);
            }
            return buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return null;
    }




    public static String sign(Map<String, String> params, String key) {
       try {
           StringBuffer buffer = new StringBuffer();
           TreeMap<String, String> treeMap = new TreeMap<>(params);
           for (Map.Entry<String, String> entry : treeMap.entrySet()) {
               if (entry.getValue() != null && !"".equals(entry.getValue()) && !"sign".equals(entry.getKey())) {
                   buffer.append(entry.getValue());
               }
           }
           buffer.append(key);
           return SHA256Util.encrypt(buffer.toString());

       }catch (Exception e){
            throw new RuntimeException(e.getMessage());
       }
    }


    public static boolean checkSign(String message, String key)  {
       try{
        String[] split = message.split("\\|", -1);
        if (split.length != 3){
            return true;
        }else {
            String inner = split[1];
            String _sign = split[2];
            return SHA256Util.encrypt(inner+key).equalsIgnoreCase(_sign);
        }
      }catch (Exception e){
          throw new RuntimeException(e.getMessage());
      }
   }


}
